using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace Survivor
{
	public partial class SimpleKnife : ViewController
	{
		private float _currentSeconds= 0;
		public float attackRange;
		public float knifeSpeed;
		public LayerMask attackTargetLayer;
		private RaycastHit2D[] _attackResult;
		void Start()
		{
			// Code Here
			_attackResult = new RaycastHit2D[20];
		}

		private void Update()
		{
			_currentSeconds += Time.deltaTime;
			if (_currentSeconds >= Global.SimpleKnifeInterval.Value)
			{
				var size = Physics2D.CircleCastNonAlloc(transform.position, attackRange, 
					Vector2.zero,_attackResult,1,attackTargetLayer);
				if (size == 0) return;

				var direction = _attackResult[0].transform.position - transform.position;
				float minDistance = direction.magnitude;
				for (int i = 1; i < size; i++)
				{
					var t = _attackResult[i].transform.position - transform.position;
					if ( t.magnitude<= minDistance)
					{
						direction = t;
					}
				}

				StartCoroutine(IGenerateKnife(direction));
				_currentSeconds = 0;
			}
		}

		private void OnDrawGizmos()
		{
			Gizmos.color = Color.red;
			Gizmos.DrawWireSphere(transform.position,attackRange);
		}

		IEnumerator IGenerateKnife(Vector2 direction)
		{
			for (int i = 0; i < Global.SimpleKnifeCount.Value + Global.FlyThingCount.Value; i++)
			{
				
				this.Knfie.Instantiate().Self((self) =>
				{
					var knife = self.GetComponent<Knife>();
					if (knife)
					{
						knife.Init(transform.position +new Vector3(0,Random.Range(-0.5f,0.5f),0),direction,knifeSpeed);
					}
				}).Show();
				yield return new WaitForSeconds(0.05f);
			}
		}
	}
}
